import { aiGenerateQuestionUsingPost } from "@/services/backend/questionController";
import { DeleteOutlined } from "@ant-design/icons";
import { Button, Card, Col, Form, Input, InputNumber, message, Modal, Pagination, Row, Spin } from "antd";
import { useEffect, useState } from "react";

interface Props {
    appId: number;
    onSubmit: (data: API.QuestionContent[]) => void;
}

const CreateQuestionsComponent = (props: Props) => {
    const { onSubmit } = props;
    const [form] = Form.useForm();
    const [questionList, setQuestionList] = useState<API.QuestionContent[]>([]);
    const [current, setCurrent] = useState(1);
    const [total, setTotal] = useState(0);
    const [visible, setVisible] = useState(false);
    const [questionNum, setQuestionNum] = useState(1);
    const [optionNum, setOptionNum] = useState(2);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setTotal(questionList.length);
        if (questionList.length === 0) {
            setCurrent(1);
        } else if (current > questionList.length) {
            setCurrent(questionList.length);
        }
    }, [questionList]);

    const { appId } = props;

    const handleAddOption = (questionIndex: number) => {
        setQuestionList(questionList.map((question, index) => {
            if (index === questionIndex) {
                return {
                    ...question,
                    options: [
                        ...(question.options || []),
                        { key: "", result: "", score: 0, value: "" }
                    ]
                };
            }
            return question;
        }));
    };

    const handleAddQuestion = () => {
        const newQuestion: API.QuestionContent = {
            title: '',
            options: []
        };
        setQuestionList([...questionList, newQuestion]);
        setCurrent(questionList.length + 1);
    };

    // 处理问题标题变更
    const handleQuestionTitleChange = (questionIndex: number, newTitle: string) => {
        setQuestionList(questionList.map((question, index) => {
            if (index === questionIndex) {
                return { ...question, title: newTitle };
            }
            return question;
        }));
    };

    const handleDeleteOption = (questionIndex: number, optionIndex: number) => {
        setQuestionList(questionList.map((question, qIndex) => {
            if (qIndex === questionIndex) {
                const updatedOptions = (question.options || []).filter((_, oIndex) => oIndex !== optionIndex);
                return { ...question, options: updatedOptions };
            }
            return question;
        }));
    };

    // 处理选项字段变更
    const handleOptionChange = (
        questionIndex: number,
        optionIndex: number,
        field: keyof API.Option,
        value: string | number
    ) => {
        setQuestionList(questionList.map((question, qIndex) => {
            if (qIndex === questionIndex) {
                const updatedOptions = (question.options || []).map((option, oIndex) => {
                    if (oIndex === optionIndex) {
                        return { ...option, [field]: value };
                    }
                    return option;
                });
                return { ...question, options: updatedOptions };
            }
            return question;
        }));
    };

    const handleSubmit = () => {
        if (questionList.length === 0) {
            message.error('请添加问题');
            return;
        }
        if (questionList.filter(item => item.options?.length === 0).length > 0) {
            console.log(questionList);
            message.error('请添加选项');
            return;
        }
        onSubmit(questionList);
    }

    // 在handleGenerateQuestions函数中添加form.setFieldsValue调用
    const handleGenerateQuestions = () => {
        setLoading(true);
        setVisible(false);
    
        aiGenerateQuestionUsingPost({
            appId,
            questionNumber: questionNum,
            optionNumber: optionNum
        }).then(res => {
            if (res.code === 0) {
                message.success('创建成功');
                if (res.data) {
                    setQuestionList(res.data);
                    setCurrent(res.data.length);
                    setTotal(res.data.length);
                    // 当数据更新后，强制更新当前显示的表单
                    if (res.data.length > 0 && current <= res.data.length) {
                        form.setFieldsValue(res.data[current - 1]);
                    }
                }
    
                setLoading(false);
            } else {
                message.error(res.message);
                setLoading(false);
            }
        })
    }

    const handleDeleteQuestion = (questionIndex: number) => {
        setQuestionList(questionList.filter((_, index) => index !== questionIndex));
    }
    
    // 另外，添加一个useEffect来监听current变化，更新表单值
    useEffect(() => {
        if (questionList.length > 0 && current <= questionList.length) {
            form.setFieldsValue(questionList[current - 1]);
        }
    }, [current, questionList]);

    useEffect(() => {
        handleAddQuestion();
    }, [])

    return (
        <>
            <Spin spinning={loading} fullscreen />
            {questionList.map((item, index) => (
                current === index + 1 && (
                    <Card key={index} title={`问题${index + 1}`} style={{ height: '400px', overflowY: 'scroll' }} extra={<Button icon={<DeleteOutlined />} onClick={()=>handleDeleteQuestion(index)}></Button>}>
                        <Form initialValues={item} form={form} layout="vertical" >
                            <Form.Item  name="title">
                                <Input placeholder="请输入问题" value={item.title} onChange={(e) => handleQuestionTitleChange(index, e.target.value)} />
                            </Form.Item>
                            {item.options?.map((option, optIndex) => (
                                <Card title={`选项${optIndex + 1}`} extra={<Button icon={<DeleteOutlined />} onClick={() => handleDeleteOption(index, optIndex)}></Button>}
                                    key={optIndex}
                                >
                                    <Row>
                                        <Col span={12}>
                                            <Form.Item
                                                label={`选项文字`}
                                                style={{ padding: 8 }}
                                            >
                                                <Input value={option.value}
                                                    onChange={(e) => handleOptionChange(index, optIndex, 'value', e.target.value)}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={12}>
                                            <Form.Item
                                                label={`选项值（如'A' 'B'）`}
                                                style={{ padding: 8 }}
                                            >
                                                <Input value={option.key}
                                                    onChange={(e) => handleOptionChange(index, optIndex, 'key', e.target.value)}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={12}>
                                            <Form.Item
                                                label={`选项得分（得分类）`}
                                                style={{ padding: 8 }}
                                            >
                                                <Input value={option.score} type="number"
                                                    onChange={(e) => handleOptionChange(index, optIndex, 'score', Number(e.target.value))}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={12}>
                                            <Form.Item
                                                label={`选项结果（测评类）`}
                                                style={{ padding: 8 }}
                                            >
                                                <Input value={option.result}
                                                    onChange={(e) => handleOptionChange(index, optIndex, 'result', e.target.value)}
                                                />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Card>

                            ))}
                            <Button
                                type="primary"
                                onClick={() => handleAddOption(index)}
                            >
                                新增选项
                            </Button>
                        </Form>
                    </Card>
                )
            ))}

            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20, gap: 10 }}>
                <Button onClick={() => { setVisible(true) }} style={{ marginRight: 'auto' }}>AI一键生成题目</Button>
                {questionList.length > 0 && (
                    <Pagination
                        align="end"
                        current={current}
                        total={total}
                        pageSize={1}
                        onChange={setCurrent}
                    />
                )}
                <Button type="dashed" onClick={handleAddQuestion}>
                    添加问题
                </Button>
                <Button type="primary" onClick={handleSubmit}>
                    添加完成
                </Button>
            </div>

            <Modal title="AI一键生成题目" open={visible} onCancel={() => setVisible(false)} onOk={handleGenerateQuestions} >
                <Form labelCol={{ span: 8 }}>
                    <Form.Item label="生成题目数量">
                        <InputNumber min={1} max={10} value={questionNum} onChange={(val) => setQuestionNum(val ? val : 0)} style={{ width: 200 }}></InputNumber>
                    </Form.Item>
                    <Form.Item label="每道题选项数量">
                        <InputNumber min={2} max={4} value={optionNum} onChange={(val) => setOptionNum(val ? val : 0)} style={{ width: 200 }}></InputNumber>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
}
export default CreateQuestionsComponent;